

package com.lj.back.manage.scaffold.common.util;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.lj.back.manage.scaffold.common.constant.HttpConstant;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;

/**
 * IP地址工具类
 * @author lv
 */
@Slf4j
public class HttpRequestUtil {

    /**
     * 工具类私有无参构造
     */
    private HttpRequestUtil(){}

	/**
	 * 获取IP地址
	 * 使用Nginx等反向代理软件， 不能通过request.getRemoteAddr()获取IP地址
	 * 如果使用了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP地址，X-Forwarded-For中第一个非unknown的有效IP字符串，则为真实IP地址
	 */
	public static String getRequestIp(HttpServletRequest request) {
    	String ip = null;
        try {
            ip = request.getHeader("x-forwarded-for");
            if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (StringUtils.isBlank(ip) || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
            }
            if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
            //使用代理，则获取第一个IP地址
            if(StringUtils.isNotBlank(ip) && ip.length() > 15) {
                if(ip.indexOf(",") > 0) {
                    ip = ip.substring(0, ip.indexOf(","));
                }
            }
        } catch (Exception e) {
        	log.error("获取IP地址异常",e);
        }
        return ip;
    }

    /**
     * 从请求头获取token
     * @param request 请求对象
     * @return token
     */
    public static String getToken(HttpServletRequest request){
        String token = request.getHeader(HttpConstant.TOKEN_HEADER_KEY_SYS);
        if (StringUtils.isBlank(token)){
            token = request.getParameter(HttpConstant.TOKEN_HEADER_KEY_SYS);
        }
        return token;
    }

    public static String getDomain(HttpServletRequest request){
        StringBuffer url = request.getRequestURL();
        return url.delete(url.length() - request.getRequestURI().length(), url.length()).toString();
    }

    public static String getOrigin(HttpServletRequest request){
        return request.getHeader("Origin");
    }
	
}
